package com.google.code.jbauble.mvc.support;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MemoryResourceLoader extends ResourceLoader {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private ViewResourceCache cache = null;
	private String path;
	@Override
	public void init(ExtendedProperties configuration) {
		path = StringUtils.nullTrim(configuration.getString("path"));
		cache = ViewResourceCache.getInstance();
	}

	@Override
	public InputStream getResourceStream(String source)
			throws ResourceNotFoundException {
		ViewResourceContext c = null;
		
		try {
			c = cache.loadView(source);
		} catch (IOException e) {
			log.error("Read file error." + source, e);
			return null;
		}
		
		if (c == null || c.getViewContent() == null)
			return null;

		return new ByteArrayInputStream(c.getViewContent().getBytes());
	}

	@Override
	public boolean isSourceModified(Resource resource) {
		return false;
	}

	@Override
	public long getLastModified(Resource resource) {
		return 0;
	}
	
}
